package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时订单，没15分钟执行一次
     */
    @Scheduled(cron = "0 15 * * * ?")
    public void processOutTimeOrder() {
        log.info("处理超时订单:{}", LocalDateTime.now());
        //查询超时订单，修改订单状态
        LocalDateTime now = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList =  ordersMapper.selectByStatusAndNowDate(Orders.PENDING_PAYMENT, now);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }
    }

    /**
     * 处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrders() {
        log.info("处理派送中的订单：{}", LocalDateTime.now());
        LocalDateTime lastDay = LocalDateTime.now().minusMinutes(60);
        List<Orders> ordersList = ordersMapper.selectByStatusAndNowDate(Orders.DELIVERY_IN_PROGRESS, lastDay);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders);
            }
        }
    }
}
